//
//  BDChatViewController.m
//  iOS_beboy
//
//  Created by wen on 2018/1/29.
//  Copyright © 2018年 com.8xiong. All rights reserved.
//

#import "BDChatViewController.h"
#import "EaseChatToolbar.h"
#import "EaseFaceView.h"
#import "EaseRecordView.h"
#import "EaseEmoji.h"
#import "EaseEmotionManager.h"
#import "BDChatSettingViewController.h"

@interface BDChatViewController ()<UITableViewDelegate, UITableViewDataSource, EaseChatBarMoreViewDelegate, EaseFacialViewDelegate, EMChatToolbarDelegate>
{
    UIMenuItem *_copyMenuItem;
    UIMenuItem *_deleteMenuItem;
    UILongPressGestureRecognizer *_lpgr;
    NSMutableDictionary *_emotionDic;
}
/*!
 @property
 @brief 底部输入控件
 */
@property (strong, nonatomic) UIView *chatToolbar;

/*!
 @property
 @brief 底部功能控件
 */
@property(strong, nonatomic) EaseChatBarMoreView *chatBarMoreView;

/*!
 @property
 @brief 底部表情控件
 */
@property(strong, nonatomic) EaseFaceView *faceView;

/*!
 @property
 @brief 底部录音控件
 */
@property(strong, nonatomic) EaseRecordView *recordView;

/*!
 @property
 @brief 菜单(消息复制,删除)
 */
@property (strong, nonatomic) UIMenuController *menuController;

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *rightButton;

@end

@implementation BDChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    CGFloat chatbarHeight = [EaseChatToolbar defaultHeight];
//    EMChatToolbarType barType = self.conversation.type == EMConversationTypeChat ? EMChatToolbarTypeChat : EMChatToolbarTypeGroup;
    EMChatToolbarType barType = EMChatToolbarTypeChat;
    self.chatToolbar = [[EaseChatToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - chatbarHeight, self.view.frame.size.width, chatbarHeight) type:barType];
    [(EaseChatToolbar *)self.chatToolbar setDelegate:self];
    self.chatToolbar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self.view addSubview:_chatToolbar];
    
    CGRect tableFrame = self.tableView.frame;
    tableFrame.size.height = self.view.frame.size.height - _chatToolbar.frame.size.height;
    self.tableView.frame = tableFrame;
    
    self.chatBarMoreView = (EaseChatBarMoreView*)[(EaseChatToolbar *)self.chatToolbar moreView];
    self.faceView = (EaseFaceView*)[(EaseChatToolbar *)self.chatToolbar faceView];
    self.recordView = (EaseRecordView*)[(EaseChatToolbar *)self.chatToolbar recordView];
    
    //Initializa the gesture recognizer
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyBoardHidden:)];
    [self.view addGestureRecognizer:tap];
    
    _lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    _lpgr.minimumPressDuration = 0.5;
    [self.tableView addGestureRecognizer:_lpgr];
    
    [self.faceView setEmotionManagers:[self emotionArray]];
    [self _setupBarButtonItem];
}

//这个是设置聊天右item方法的
- (void)_setupBarButtonItem
{
    self.rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    //单聊
    if (_conversation.conversationType == kJMSGConversationTypeSingle) {
        [self.rightButton setImage:[UIImage imageNamed:@"message_set_geren"] forState:UIControlStateNormal];
    }
    else{//群聊
        [self.rightButton setImage:[UIImage imageNamed:@"message_set_group"] forState:UIControlStateNormal];
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    [[self.rightButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (_conversation.conversationType == kJMSGConversationTypeSingle) {
            BDChatSettingViewController *chatSetVC = [[BDChatSettingViewController alloc] init];
            chatSetVC.conversation = self.conversation;
            [self.navigationController pushViewController:chatSetVC animated:YES];
        }else if (_conversation.conversationType == kJMSGConversationTypeGroup) {
//            BDGroupSettingViewController *groupSettingVC = [[BDGroupSettingViewController alloc] init];
//            groupSettingVC.conversation = self.conversation;
//            NSString *groupPath = [DocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"group_%@.plist", self.conversation.conversationId]];
//            groupSettingVC.groupModel = [BDChatGroupModel mj_objectWithKeyValues:[NSDictionary dictionaryWithContentsOfFile:groupPath]];
//            [self.navigationController pushViewController:groupSettingVC animated:YES];
        }
    }];
}

//这里是设置当前显示哪些表情的
- (NSArray*)emotionArray{
    NSMutableArray *emotions = [NSMutableArray array];
    for (NSString *name in [EaseEmoji allEmoji]) {
        EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:name emotionThumbnail:name emotionOriginal:name emotionOriginalURL:@"" emotionType:EMEmotionDefault];
        [emotions addObject:emotion];
    }
    EaseEmotion *temp = [emotions objectAtIndex:0];
    EaseEmotionManager *managerDefault = [[EaseEmotionManager alloc] initWithType:EMEmotionDefault emotionRow:3 emotionCol:7 emotions:emotions tagImage:[UIImage imageNamed:temp.emotionId]];
    
    NSMutableArray *emotionGifs = [NSMutableArray array];
    _emotionDic = [NSMutableDictionary dictionary];
    NSArray *names = @[@"icon_002",@"icon_007",@"icon_010",@"icon_012",@"icon_013",@"icon_018",@"icon_019",@"icon_020",@"icon_021",@"icon_022",@"icon_024",@"icon_027",@"icon_029",@"icon_030",@"icon_035",@"icon_040"];
    int index = 0;
    for (NSString *name in names) {
        index++;
        EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:[NSString stringWithFormat:ASLocalizedString(@"[示例%d]"),index] emotionId:[NSString stringWithFormat:@"em%d",(1000 + index)] emotionThumbnail:[NSString stringWithFormat:@"%@_cover",name] emotionOriginal:[NSString stringWithFormat:@"%@",name] emotionOriginalURL:@"" emotionType:EMEmotionGif];
        [emotionGifs addObject:emotion];
        [_emotionDic setObject:emotion forKey:[NSString stringWithFormat:@"em%d",(1000 + index)]];
    }
    EaseEmotionManager *managerGif= [[EaseEmotionManager alloc] initWithType:EMEmotionGif emotionRow:2 emotionCol:4 emotions:emotionGifs tagImage:[UIImage imageNamed:@"icon_002_cover"]];
    
    return @[managerDefault,managerGif];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chatcell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"chatcell"];
    }
    return cell;
}

#pragma mark - EMChatToolbarDelegate

- (void)chatToolbarDidChangeFrameToHeight:(CGFloat)toHeight{
    [UIView animateWithDuration:0.3 animations:^{
        CGRect rect = self.tableView.frame;
        rect.origin.y = 0;
        rect.size.height = self.view.frame.size.height - toHeight;
        self.tableView.frame = rect;
    }];
}

- (void)inputTextViewWillBeginEditing:(EaseTextView *)inputTextView
{
    if (_menuController == nil) {
        _menuController = [UIMenuController sharedMenuController];
    }
    [_menuController setMenuItems:nil];
}

- (void)didSendText:(NSString *)text
{
//    if (text && text.length > 0) {
//        [self sendTextMessage:text];
//        [self.atTargets removeAllObjects];
//    }
}

- (BOOL)didInputAtInLocation:(NSUInteger)location
{
//    if ([self.delegate respondsToSelector:@selector(messageViewController:selectAtTarget:)] && self.conversation.type == EMConversationTypeGroupChat) {
//        location += 1;
//        __weak typeof(self) weakSelf = self;
//        [self.delegate messageViewController:self selectAtTarget:^(EaseAtTarget *target) {
//            __strong EaseMessageViewController *strongSelf = weakSelf;
//            if (strongSelf && target) {
//                if ([target.userId length] || [target.nickname length]) {
//                    [strongSelf.atTargets addObject:target];
//                    NSString *insertStr = [NSString stringWithFormat:@"%@ ", target.nickname ? target.nickname : target.userId];
//                    EaseChatToolbar *toolbar = (EaseChatToolbar*)strongSelf.chatToolbar;
//                    NSMutableString *originStr = [toolbar.inputTextView.text mutableCopy];
//                    NSUInteger insertLocation = location > originStr.length ? originStr.length : location;
//                    [originStr insertString:insertStr atIndex:insertLocation];
//                    toolbar.inputTextView.text = originStr;
//                    toolbar.inputTextView.selectedRange = NSMakeRange(insertLocation + insertStr.length, 0);
//                    [toolbar.inputTextView becomeFirstResponder];
//                }
//            }
//            else if (strongSelf) {
//                EaseChatToolbar *toolbar = (EaseChatToolbar*)strongSelf.chatToolbar;
//                [toolbar.inputTextView becomeFirstResponder];
//            }
//        }];
//        EaseChatToolbar *toolbar = (EaseChatToolbar*)self.chatToolbar;
//        toolbar.inputTextView.text = [NSString stringWithFormat:@"%@@", toolbar.inputTextView.text];
//        [toolbar.inputTextView resignFirstResponder];
//        return YES;
//    }
//    else {
        return NO;
//    }
}

- (BOOL)didDeleteCharacterFromLocation:(NSUInteger)location
{
//    EaseChatToolbar *toolbar = (EaseChatToolbar*)self.chatToolbar;
//    if ([toolbar.inputTextView.text length] == location + 1) {
//        //delete last character
//        NSString *inputText = toolbar.inputTextView.text;
//        NSRange range = [inputText rangeOfString:@"@" options:NSBackwardsSearch];
//        if (range.location != NSNotFound) {
//            if (location - range.location > 1) {
//                NSString *sub = [inputText substringWithRange:NSMakeRange(range.location + 1, location - range.location - 1)];
//                for (EaseAtTarget *target in self.atTargets) {
//                    if ([sub isEqualToString:target.userId] || [sub isEqualToString:target.nickname]) {
//                        inputText = range.location > 0 ? [inputText substringToIndex:range.location] : @"";
//                        toolbar.inputTextView.text = inputText;
//                        toolbar.inputTextView.selectedRange = NSMakeRange(inputText.length, 0);
//                        [self.atTargets removeObject:target];
//                        return YES;
//                    }
//                }
//            }
//        }
//    }
    return NO;
}

- (void)didSendText:(NSString *)text withExt:(NSDictionary*)ext
{
//    if ([ext objectForKey:EASEUI_EMOTION_DEFAULT_EXT]) {
//        EaseEmotion *emotion = [ext objectForKey:EASEUI_EMOTION_DEFAULT_EXT];
//        if (self.dataSource && [self.dataSource respondsToSelector:@selector(emotionExtFormessageViewController:easeEmotion:)]) {
//            NSDictionary *ext = [self.dataSource emotionExtFormessageViewController:self easeEmotion:emotion];
//            [self sendTextMessage:emotion.emotionTitle withExt:ext];
//        } else {
//            [self sendTextMessage:emotion.emotionTitle withExt:@{MESSAGE_ATTR_EXPRESSION_ID:emotion.emotionId,MESSAGE_ATTR_IS_BIG_EXPRESSION:@(YES)}];
//        }
//        return;
//    }
//    if (text && text.length > 0) {
//        [self sendTextMessage:text withExt:ext];
//    }
}

- (void)didStartRecordingVoiceAction:(UIView *)recordView
{
//    if ([self.delegate respondsToSelector:@selector(messageViewController:didSelectRecordView:withEvenType:)]) {
//        [self.delegate messageViewController:self didSelectRecordView:recordView withEvenType:EaseRecordViewTypeTouchDown];
//    } else {
//        if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
//            [(EaseRecordView *)self.recordView recordButtonTouchDown];
//        }
//    }
    
//    if ([self _canRecord]) {
//        EaseRecordView *tmpView = (EaseRecordView *)recordView;
//        tmpView.center = self.view.center;
//        [self.view addSubview:tmpView];
//        [self.view bringSubviewToFront:recordView];
//        int x = arc4random() % 100000;
//        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
//        NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
//
//        [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error)
//         {
//             if (error) {
//                 NSLog(@"%@",NSEaseLocalizedString(@"message.startRecordFail", @"failure to start recording"));
//             }
//         }];
//    }
}

- (void)didCancelRecordingVoiceAction:(UIView *)recordView
{
//    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
//    if ([self.delegate respondsToSelector:@selector(messageViewController:didSelectRecordView:withEvenType:)]) {
//        [self.delegate messageViewController:self didSelectRecordView:recordView withEvenType:EaseRecordViewTypeTouchUpOutside];
//    } else {
//        if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
//            [(EaseRecordView *)self.recordView recordButtonTouchUpOutside];
//        }
//        [self.recordView removeFromSuperview];
//    }
}

- (void)didFinishRecoingVoiceAction:(UIView *)recordView
{
//    if ([self.delegate respondsToSelector:@selector(messageViewController:didSelectRecordView:withEvenType:)]) {
//        [self.delegate messageViewController:self didSelectRecordView:recordView withEvenType:EaseRecordViewTypeTouchUpInside];
//    } else {
//        if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
//            [(EaseRecordView *)self.recordView recordButtonTouchUpInside];
//        }
//        [self.recordView removeFromSuperview];
//    }
//    __weak typeof(self) weakSelf = self;
//    [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
//        if (!error) {
//            [weakSelf sendVoiceMessageWithLocalPath:recordPath duration:aDuration];
//        }
//        else {
//            [weakSelf showHudInView:self.view hint:error.domain];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [weakSelf hideHud];
//            });
//        }
//    }];
}

- (void)didDragInsideAction:(UIView *)recordView
{
//    if ([self.delegate respondsToSelector:@selector(messageViewController:didSelectRecordView:withEvenType:)]) {
//        [self.delegate messageViewController:self didSelectRecordView:recordView withEvenType:EaseRecordViewTypeDragInside];
//    } else {
//        if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
//            [(EaseRecordView *)self.recordView recordButtonDragInside];
//        }
//    }
}

- (void)didDragOutsideAction:(UIView *)recordView
{
//    if ([self.delegate respondsToSelector:@selector(messageViewController:didSelectRecordView:withEvenType:)]) {
//        [self.delegate messageViewController:self didSelectRecordView:recordView withEvenType:EaseRecordViewTypeDragOutside];
//    } else {
//        if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
//            [(EaseRecordView *)self.recordView recordButtonDragOutside];
//        }
//    }
}

#pragma mark - EaseChatBarMoreViewDelegate

- (void)moreView:(EaseChatBarMoreView *)moreView didItemInMoreViewAtIndex:(NSInteger)index
{
//    if ([self.delegate respondsToSelector:@selector(messageViewController:didSelectMoreView:AtIndex:)]) {
//        [self.delegate messageViewController:self didSelectMoreView:moreView AtIndex:index];
//        return;
//    }
}

- (void)moreViewPhotoAction:(EaseChatBarMoreView *)moreView
{
    // Hide the keyboard
    [self.chatToolbar endEditing:YES];
    
    // Pop image picker
//    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
//    [self presentViewController:self.imagePicker animated:YES completion:NULL];
//
//    self.isViewDidAppear = NO;
//    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:YES];
}

- (void)moreViewTakePicAction:(EaseChatBarMoreView *)moreView
{
    // Hide the keyboard
    [self.chatToolbar endEditing:YES];
    
//#if TARGET_IPHONE_SIMULATOR
//    [self showHint:NSEaseLocalizedString(@"message.simulatorNotSupportCamera", @"simulator does not support taking picture")];
//#elif TARGET_OS_IPHONE
//    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
//    [self presentViewController:self.imagePicker animated:YES completion:NULL];
//    self.isViewDidAppear = NO;
//    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:YES];
//#endif
}

- (void)moreViewTakeLetterVedio:(EaseChatBarMoreView *)moreView{
    // Hide the keyboard
    [self.chatToolbar endEditing:YES];
    
#if TARGET_IPHONE_SIMULATOR
    [self showHint:NSEaseLocalizedString(@"message.simulatorNotSupportCamera", @"simulator does not support taking picture")];
#elif TARGET_OS_IPHONE
    
    //    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeMovie];
    //    [self presentViewController:self.imagePicker animated:YES completion:NULL];
//    BDtakeLetterVideoViewController *takeLetterVideoVC = [[BDtakeLetterVideoViewController alloc] init];
//    takeLetterVideoVC.HSeconds = 30;//设置可录制最长时间
//    takeLetterVideoVC.takeBlock = ^(id item) {
//        if ([item isKindOfClass:[NSURL class]]) {
//            NSURL *videoURL = item;
//            //视频url
//            NSURL *mp4 = [self _convert2Mp4:videoURL];
//            NSFileManager *fileman = [NSFileManager defaultManager];
//            if ([fileman fileExistsAtPath:videoURL.path]) {
//                NSError *error = nil;
//                [fileman removeItemAtURL:videoURL error:&error];
//                if (error) {
//                    NSLog(@"failed to remove file, error:%@.", error);
//                }
//            }
//            [self sendVideoMessageWithURL:mp4];
//
//        } else {
//            //图片
//
//        }
//    };
//    [self presentViewController:takeLetterVideoVC animated:YES completion:nil];
//    self.isViewDidAppear = NO;
//    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:YES];
#endif
}

- (void)moreViewLocationAction:(EaseChatBarMoreView *)moreView
{
    // Hide the keyboard
    [self.chatToolbar endEditing:YES];
    
//    __weak EaseMessageViewController *weakSelf = self;
//    BDPubishLocationViewController *locationVC = [[BDPubishLocationViewController alloc] initWithFinishBlock:^(AMapPOI *poi) {
//        [weakSelf sendLocationMessageLatitude:poi.location.latitude longitude:poi.location.longitude andAddress:poi.address];
//    }];
//    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:locationVC] animated:YES completion:nil];
}

/*
 *  语音聊天按钮点击方法
 */
- (void)moreViewAudioCallAction:(EaseChatBarMoreView *)moreView
{
    // Hide the keyboard
    [self audioCallAndVideoCall];
}

/*
 *  视频聊天按钮点击方法
 */
- (void)moreViewVideoCallAction:(EaseChatBarMoreView *)moreView
{
    // Hide the keyboard
    [self audioCallAndVideoCall];
}

- (void)audioCallAndVideoCall{
    [self.chatToolbar endEditing:YES];
    
//    [LPActionSheet showActionSheetWithTitle:nil
//                          cancelButtonTitle:ASLocalizedString(@"取消")destructiveButtonTitle:nil
//                          otherButtonTitles:@[ASLocalizedString(@"语音通话"), ASLocalizedString(@"视频聊天")] handler:^(LPActionSheet *actionSheet, NSInteger index) {
//                              if (index > 0) {
//                                  [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_CALL object:@{@"chatter":self.conversation.conversationId, @"type":[NSNumber numberWithInt:index - 1]}];
//                              }
//                          }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
